<?php
namespace app\controller;

use app\BaseController;
use app\service\DtkService;
use app\service\GoodsService;
use app\service\CategoryService;
use app\service\ShopService;
use think\App;
use think\exception\HttpException;
use think\facade\View;

class Item extends BaseController
{
    protected $categoryService;
    protected $goodsService;
    private $shopService;
    private $dtkService;

    /**
     * Category constructor.
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->categoryService = app()->make(CategoryService::class);
        $this->goodsService = app()->make(GoodsService::class);
        $this->shopService = app()->make(ShopService::class);
        $this->dtkService = app()->make(DtkService::class);
    }

    public function index($id): string
    {
        $detail = $this->goodsService->queryDetailByDtkGoodsId($id);
        if (empty($detail)) {
            $from = $this->request->get('f');
            if (!empty($from)) {
                $detail = $this->dtkService->getGoodsDetail($id);
            }
            if (empty($detail)) {
                return View::fetch('/error/index', array('msg'=>'抱歉，商品不存在'));
            }
        }
        $linkData = $this->dtkService->getPrivilegeLink($detail['goods_id']);
        if (empty($linkData)) {
            return View::fetch('/error/index', array('msg'=>'抱歉，商品优惠信息获取失败'));
        }
        $detail = array_merge($detail, $linkData);
        $detail['full_cut'] = '';
        if ($detail['discount_full'] > 0 && $detail['discount_cut'] > 0) {
            $detail['full_cut'] = '满'.$detail['discount_full'].'减'.$detail['discount_cut'];
        }
        $category = $this->categoryService->queryDetail($detail['cid']);
        $data['category'] = $category;
        $data['detail'] = $detail;
        $data['shop'] = $this->shopService->queryDetailBySellerId($detail['seller_id']);
        //$data['hotSales'] = $this->goodsService->queryListByNum(array(), 'month_sales desc',5);
        $data['categoryHotSales'] = $this->goodsService->queryListByNum('cid = '.$category['id'], 'month_sales desc',5);
        $data['cid'] = $detail['cid'];
        return View::fetch('/goods/detail', $data);
    }
}
